package orchestration.android.demo.library;

import orchestration.android.demo.library.model.Library;
import android.app.ListActivity;
import android.content.Intent;
import android.database.Cursor;
import orchestration.android.R;
import android.os.Bundle;
import android.view.View;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;

public abstract class ListBookActivity extends ListActivity {

	   
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.loan_book);
		fillData();
	}
	
	protected abstract Cursor getBookCursor();
	
	protected abstract void onBookChosen(long id);
	
	  private void fillData() {
			Cursor bookCursor= getBookCursor();
	        startManagingCursor(bookCursor);
	        
	        // Create an array to specify the fields we want to display in the list (only TITLE)
	        String[] from = new String[]{Library.KEY_ID,Library.KEY_TITLE,Library.KEY_AUTHOR};
	        
	        // and an array of the fields we want to bind those fields to (in this case just text1)
	        int[] to = new int[]{R.id.text0,R.id.text1,R.id.text2};
	        
	        // Now create a simple cursor adapter and set it to display
	        SimpleCursorAdapter books = 
	        	    new SimpleCursorAdapter(this, R.layout.book_row, bookCursor, from, to);
	        setListAdapter(books);
	    }
	
	  @Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		super.onListItemClick(l, v, position, id);
		onBookChosen(id);
		prepareOutput(id);
		finish();
	}
	protected void prepareOutput(long id) {
			Bundle b= new Bundle();
			b.putLong(Library.KEY_ID, id);
			Intent i = new Intent();
			i.putExtras(b);
			setResult(RESULT_OK,i);
		}
}
